package com.navi.loaddata.loadService.impl.opeHis;

import com.navi.loaddata.core.errorLog.ErrorCode;
import com.navi.loaddata.core.etlException.ETLException2;
import com.navi.loaddata.core.gpEntity.hisToGP.*;
import com.navi.loaddata.core.mysqlEntity.EtlConfDModel;
import com.navi.loaddata.core.util.JacksonUtil;
import com.navi.loaddata.core.util.LoggerUtil;
import com.navi.loaddata.core.util.ProcessUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.List;

//import com.navi.loaddata.utils.JdbcUtil;

@Service
public class LoadWmsShipService {

    private static final Logger logger = LoggerFactory.getLogger(LoadWmsShipService.class);
    @Autowired
    private AmqpTemplate rabbitTemplate;
    @Autowired
    private LoadWmsInfoService loadWmsInfoService;

    public String[] loadWmsShipDataMain(EtlConfDModel etlConfD) throws Exception {
        String[] resMsg = loadWmsShip(etlConfD);
        logger.info("loadWmsShipDataMain finish");
        return resMsg;
    }

    private String[] loadWmsShip(EtlConfDModel etlConfD) throws Exception {
        String[] resMsg = new String[3];
        int okCnt = 0;
        int errCnt = 0;
        String errMsg = null;


        List<ProductHis> productHisList = loadWmsInfoService.getWmsShipInfo(etlConfD);
        logger.info("WMS SHIP 共{}笔数据", productHisList.size());


        if (!productHisList.isEmpty()) {
            for (ProductHis productHis : productHisList) {
                try {
                    if (productHis.getProd_id().contains("DUMMY")) {
                        logger.warn("glassId={} prodId 包含 DUMMY，跳过", productHis.getGlass_id_o());
                        continue;
                    }
                    if (!"A".equals(productHis.getGlass_id_o().substring(0,1)) && !"C".equals(productHis.getGlass_id_o().substring(0,1))) {
                        logger.warn("glassId={} glassId 信息不符合要求，跳过", productHis.getGlass_id_o());
                        continue;
                    }

                    //ext表
                    WppShtOpeHisExt wppExt = loadWmsInfoService.getExtInfo(productHis.getGlass_id_o());
                    saveCSht(productHis, wppExt);

                    logger.info("glassId={} lgofTimestamp={} 保存成功。",
                            productHis.getGlass_id_o(), productHis.getLogof_timestamp());
                    loadWmsInfoService.clearObject(wppExt);
                    okCnt++;
                } catch (ETLException2 e) {
                    String err = e.getErrorCode().getErrorMsg() + "错误原因：" + e.getErrMsg();
                    logger.error("glassId={} {},错误原因：{}",
                            productHis.getGlass_id_o(), e.getErrorCode().getErrorMsg(), LoggerUtil.stackTraceToString(e));
                    if (StringUtils.isEmpty(err)) {
                        errMsg = "glassId=" + productHis.getGlass_id_o()+ " " + err + "\n";
                    } else {
                        errMsg += "glassId=" + productHis.getGlass_id_o() + " " + err + "\n";

                    }
                    errCnt++;
                } catch (Exception e) {
                    String err = LoggerUtil.stackTraceToString(e);
                    logger.error("glassId={} 保存错误，错误原因：{}",
                            productHis.getGlass_id_o(), err);
                    if (StringUtils.isEmpty(err)) {
                        errMsg = "glassId=" + productHis.getGlass_id_o()  + " " + err + "\n";
                    } else {
                        errMsg += "glassId=" + productHis.getGlass_id_o() + " " + err + "\n";

                    }
                    errCnt++;
                }
            }
        } else {
            logger.info("没有此区间的数据。"); // todo print log & save etl data
        }
        resMsg[0] = String.valueOf(okCnt);
        resMsg[1] = String.valueOf(errCnt);
        resMsg[2] = errMsg;

        return resMsg;
    }


    public void saveCSht(ProductHis prodHis, WppShtOpeHisExt wppExt) throws Exception {
//        String shop_id = "OC";
        String glass_id_o = ProcessUtil.getStringS(prodHis.getGlass_id_o());
        String ope_id = "WMS";
        String sn = ProcessUtil.getStringS(prodHis.getSn());
        String grade_wns_ship = ProcessUtil.getStringS(prodHis.getGrade_wns_ship());
        String ppbox_id = ProcessUtil.getStringS(prodHis.getPpbox_id());
        String pallet_id = ProcessUtil.getStringS(prodHis.getPallet_id());
        String in_wms_po_id = ProcessUtil.getStringS(prodHis.getIn_wms_po_id());
        String salesorder_id = ProcessUtil.getStringS(prodHis.getSalesorder_id());
        Timestamp logof_timestamp = prodHis.getLogof_timestamp();

            WppCshtOpeHis wppCshtOpe = new WppCshtOpeHis();

            wppCshtOpe.setGlassId(glass_id_o);
            wppCshtOpe.setOpeId(ope_id);
            wppCshtOpe.setLogofTimestamp(logof_timestamp);
            wppCshtOpe.setOpeTblName("wpp_csht_ope_his");

            wppExt.setSn(sn);
            wppExt.setGradeWnsShip(grade_wns_ship);
            wppExt.setPpboxId(ppbox_id);
            wppExt.setPalletId(pallet_id);
            wppExt.setIn_wms_po_id(in_wms_po_id);
            wppExt.setSalesorder_id(salesorder_id);
            wppExt.setOpeTblName("wpp_sht_ope_his_ext");
            //modify by LynnSea

            try {
                rabbitTemplate.convertAndSend("qmsExchange", "wpp_csht_ope_his", JacksonUtil.toJSONStr(wppCshtOpe));
                rabbitTemplate.convertAndSend("qmsExchange", "wpp_sht_ope_his_ext", JacksonUtil.toJSONStr(wppExt));
            } catch (Exception e) {
                logger.error(LoggerUtil.stackTraceToString(e));
                throw new ETLException2(ErrorCode.ERROR_RABBITMQ_OPEHIS_CSHT,e);
            }
    }
}
